<template>
    <div class="crud-container">
        <!-- 搜索区域 -->
        <div class="search-area">
            <el-form :inline="true" :model="searchForm" class="search-form">

                <el-form-item label="商品名称" class="el-formitem">
                    <el-input v-model="searchForm.couponName" placeholder="请输入秒杀的优惠券名字" clearable />
                </el-form-item>
                <el-form-item label="秒杀类型" class="el-formitem">
                    <el-select v-model="searchForm.couponType" placeholder="请选择优惠券的类型" clearable>
                        <el-option label="满减" value="0" />
                        <el-option label="折扣" value="1" />
                    </el-select>
                </el-form-item>
                <el-form-item label="秒杀状态" class="el-formitem">
                    <el-select v-model="searchForm.flashSaleStatus" placeholder="请选择状态" clearable>
                        <el-option label="正在进行" value="0" />
                        <el-option label="秒杀已结束" value="1" />
                        <el-option label="秒杀未开始" value="2" />
                    </el-select>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="handleSearch">
                        <el-icon>
                            <Search />
                        </el-icon>搜索
                    </el-button>
                    <el-button @click="resetSearch">
                        <el-icon>
                            <Refresh />
                        </el-icon>重置
                    </el-button>
                </el-form-item>
            </el-form>
        </div>

        <!-- 操作按钮区域 -->
        <div class="operation-area">
            <el-button type="primary" @click="handleAdd">
                <el-icon>
                    <Plus />
                </el-icon>新增
            </el-button>
            <el-button type="danger" :disabled="!selectedRows.length" @click="handleBatchDelete">
                <el-icon>
                    <Delete />
                </el-icon>批量删除
            </el-button>
        </div>

        <!-- 表格区域 -->
        <div class="table-area">
            <el-table v-loading="loading" :data="tableData" border style="width: 100%"
                @selection-change="handleSelectionChange" row-key="seckillId">
                <el-table-column type="selection" width="55" :selectable="(row) => new Date()>new Date(row.seckillEndTime)" />
                <el-table-column prop="seckillId" label="编号" width="55" />
                <el-table-column prop="couponName" label="优惠券名称" width="150" />
                <el-table-column prop="couponType" label="优惠券类型" width="80">
                    <template #default="{ row }">
                        <el-tag :type="row.couponType === 1 ? 'warning' : 'primary'">
                            {{ row.couponType === 1 ? '折扣' : '满减' }}
                        </el-tag>
                    </template>
                </el-table-column>
                <el-table-column prop="seckillNum" label="秒杀的数量" width="80" />
                <el-table-column prop="limitNum" label="限购的数量" width="80" />
                <el-table-column prop="seckillCreateTime" label="发布时间" width="180" />
                <el-table-column prop="seckillStartTime" label="开始时间" width="180" />
                <el-table-column prop="seckillEndTime" label="结束时间" width="180" />
                <el-table-column prop="seckillStatus" label="秒杀状态" width="100">
                    <template #default="{ row }">
                        <el-tag :type="row.seckillStatus === 0 ? 'success' : 'danger'">
                            {{ row.seckillStatus === 0 ? '正常' : '删除' }}
                        </el-tag>
                    </template>
                </el-table-column>
                <el-table-column label="操作" width="200" fixed="right">
                    <template #default="{ row }">
                        <el-button type="primary" link @click="handleEdit(row)" :disabled="new Date()>new Date(row.seckillStartTime)">
                            <el-icon>
                                <Edit />
                            </el-icon>编辑
                        </el-button>
                        <el-button type="danger" link @click="handleDelete(row)" :disabled="new Date()<new Date(row.seckillEndTime)">
                            <el-icon>
                                <Delete />
                            </el-icon>删除
                        </el-button>
                    </template>
                </el-table-column>
            </el-table>
        </div>

        <!-- 分页区域 -->
        <div class="pagination-area">
            <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize" :page-sizes="[2, 3, 4, 5]"
                :total="total" layout="total, sizes, prev, pager, next, jumper" @size-change="handleSizeChange"
                @current-change="handleCurrentChange" />
        </div>

        <!-- 批量新增对话框 -->
        <el-dialog v-model="showBatchAddDialog" title="批量新增秒杀活动" width="900px" :destroy-on-close="true">
            <div class="batch-add-container">
                <el-form :model="batchForm" label-width="100px" ref="batchFormRef" :rules="batchRules">
                    <el-form-item label="选择优惠券" prop="selectedCoupons">
                        <el-select
                            v-model="batchForm.selectedCoupons"
                            multiple
                            filterable
                            collapse-tags
                            :reserve-keyword="false"
                            placeholder="请选择要参与秒杀的优惠券"
                            style="width: 600px"
                            value-key="couponId"
                            @change="handleCouponSelectChange"
                        >
                            <el-option
                                v-for="item in couponOptions"
                                :key="item.templateId"
                                :label="item.couponName"
                                :value="item.templateId"
                            >
                                <span>{{ item.couponName }}</span>
                                <span style="float: right; color: #8492a6; font-size: 13px">
                                    {{ item.couponType === 1 ? '折扣券' : '满减券' }}
                                </span>
                            </el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="秒杀数量" prop="seckillNum">
                        <el-input-number v-model="batchForm.seckillNum" :min="1" :max="999" style="width: 180px" />
                    </el-form-item>
                    <el-form-item label="限购数量" prop="limitNum">
                        <el-input-number v-model="batchForm.limitNum" :min="1" :max="999" style="width: 180px" />
                    </el-form-item>
                    <el-form-item label="开始时间" prop="startTime" class="time-picker-item">
                        <el-date-picker
                            v-model="batchForm.startTime"
                            type="datetime"
                            placeholder="选择开始时间"
                            format="YYYY-MM-DD HH:mm:ss"
                            value-format="YYYY-MM-DD HH:mm:ss"
                            style="width: 250px"
                            :default-time="new Date(2000, 1, 1, 0, 0, 0)"
                        />
                    </el-form-item>
                    <el-form-item label="结束时间" prop="endTime" class="time-picker-item">
                        <el-date-picker
                            v-model="batchForm.endTime"
                            type="datetime"
                            placeholder="选择结束时间"
                            format="YYYY-MM-DD HH:mm:ss"
                            value-format="YYYY-MM-DD HH:mm:ss"
                            style="width: 250px"
                            :default-time="new Date(2000, 1, 1, 23, 59, 59)"
                        />
                    </el-form-item>
                </el-form>

                <!-- 已选优惠券预览 -->
                <div class="selected-preview" v-if="selectedCouponDetails.length > 0">
                    <h3>已选择 {{ selectedCouponDetails.length }} 个优惠券：</h3>
                    <el-table :data="selectedCouponDetails" border style="width: 100%">
                        <el-table-column prop="couponName" label="优惠券名称" />
                        <el-table-column prop="couponType" label="类型" width="100">
                            <template #default="{ row }">
                                {{ row.couponType === 1 ? '折扣券' : '满减券' }}
                            </template>
                        </el-table-column>
                    </el-table>
                </div>
            </div>
            <template #footer>
                <el-button @click="showBatchAddDialog = false">取消</el-button>
                <el-button type="primary" @click="submitBatchAdd" :disabled="!selectedCouponDetails.length">确定</el-button>
            </template>
        </el-dialog>

        <!-- 编辑对话框 -->
        <el-dialog v-model="showEditDialog" title="编辑秒杀活动" width="600px" :destroy-on-close="true">
            <el-form :model="editForm" label-width="100px" ref="editFormRef" :rules="editRules">
                <el-form-item label="优惠券名称">
                    <el-input v-model="editForm.couponName" disabled />
                </el-form-item>
                <el-form-item label="优惠券类型">
                    <el-tag :type="editForm.couponType === 1 ? 'warning' : 'primary'" disable-transitions>
                        {{ editForm.couponType === 1 ? '折扣券' : '满减券' }}
                    </el-tag>
                </el-form-item>
                <el-form-item label="开始时间" prop="seckillStartTime">
                    <el-date-picker
                        v-model="editForm.seckillStartTime"
                        type="datetime"
                        placeholder="选择开始时间"
                        format="YYYY-MM-DD HH:mm:ss"
                        value-format="YYYY-MM-DD HH:mm:ss"
                        style="width: 250px"
                        :disabled-date="disableBeforeNow"
                    />
                </el-form-item>
                <el-form-item label="限购数量">
                    <el-input-number v-model="editForm.limitNum" disabled style="width: 180px" />
                </el-form-item>
                <el-form-item label="秒杀数量" prop="seckillNum">
                    <el-input-number v-model="editForm.seckillNum" :min="1" :max="999" style="width: 180px" />
                </el-form-item>
                <el-form-item label="结束时间" prop="seckillEndTime">
                    <el-date-picker
                        v-model="editForm.seckillEndTime"
                        type="datetime"
                        placeholder="选择结束时间"
                        format="YYYY-MM-DD HH:mm:ss"
                        value-format="YYYY-MM-DD HH:mm:ss"
                        style="width: 250px"
                        :disabled-date="disableBeforeNow"
                    />
                </el-form-item>
            </el-form>
            <template #footer>
                <el-button @click="showEditDialog = false">取消</el-button>
                <el-button type="primary" @click="submitEdit">确定</el-button>
            </template>
        </el-dialog>
    </div>
</template>

<script setup>
import { ref } from "vue"; // 确保导入 ref
import request from "@/utils/request";
import * as ElementPlusIconsVue from "@element-plus/icons-vue";
import { Fold, Expand, ArrowDown, Search, Refresh, Plus, Delete, Edit, View } from "@element-plus/icons-vue";
import { ElMessage, ElMessageBox, messageConfig } from "element-plus";
const loading = ref(false); //表格是否有数据
const tableData = ref([]); //表格数据
const selectedRows = ref([]); //选择框选中数据
const currentPage = ref(1); //当前页
const pageSize = ref(2); //每页可有的条数
const total = ref(0);

// 搜索表单数据
const searchForm = ref({
    couponName: null,
    couponType: null,
    flashSaleStatus: null,
    page: 1,
    pageSize: 2,
});
//搜索按钮
const handleSearch = () => {
    console.log(searchForm.value);
    selectKillList();
};
//重置搜索数据
const resetSearch = () => {
    searchForm.value = {
        couponName: null,
        couponType: null,
        flashSaleStatus: null,
        page: 1,
        pageSize: 2,
    };
    selectKillList();
};
//查找优惠券秒杀列表
const selectKillList = () => {
    request.get('/sekill/select', searchForm.value // 直接传递 searchForm.value 作为 params
    ).then((res) => {
        tableData.value = res.data.killList.list;
        total.value = res.data.count;
        console.log(tableData.value);
    }).catch((err) => {
        ElMessage.error('因网络波动，查询失败');
        console.error('获取失败：', err)
    })
}
//页面初始查询数据
selectKillList();
// 分页大小改变
const handleSizeChange = (val) => {
    pageSize.value = val;
    searchForm.value.pageSize = val;
    selectKillList();
}
// 页码改变
const handleCurrentChange = (val) => {
    currentPage.value = val;
    searchForm.value.page = val;
    selectKillList();
}
//选择框选中的值
const handleSelectionChange = (rows) => {
    selectedRows.value = rows;
    console.log("Selected rows:", rows);
};
//清空新增或编辑中的表单数据
const resetAddFrom = () => {
    // 重置表单
    batchForm.value = {
    selectedCoupons: [],
    seckillNum: 1,
    limitNum: 1,
    startTime: '',
    endTime: ''
    };
    selectedCouponDetails.value = [];
};
//新增按钮
const handleAdd = () => {
    showBatchAddDialog.value = true;
    // 获取可选优惠券列表
    loadCouponOptions();
    resetAddFrom();
};


// 新增相关的响应式变量
const showBatchAddDialog = ref(false);

// 新增秒杀优惠券选择
const couponOptions = ref([]); // 可选的优惠券列表
const selectedCouponDetails = ref([]); // 已选择的优惠券详细信息
const batchFormRef = ref(null);

// 批量新增表单数据
const batchForm = ref({
    selectedCoupons: [], // 存储选中的优惠券对象数组
    seckillNum: 1,
    limitNum: 1,
    startTime: '',
    endTime: ''
});
// 验证新增表单结束时间必须大于开始时间
const validateBatchEndTime = (rule, value, callback) => {
    if (batchForm.value.startTime && value) {
        if (new Date(value) <= new Date(batchForm.value.startTime)) {
            callback(new Error('结束时间必须大于开始时间'));
        } else {
            callback();
        }
    } else {
        callback();
    }
};
// 批量新增表单验证规则
const batchRules = {
    selectedCoupons: [
        { required: true, message: '请选择要参与秒杀的优惠券', trigger: 'change' }
    ],
    seckillNum: [
        { required: true, message: '请输入秒杀数量', trigger: 'blur' }
    ],
    limitNum: [
        { required: true, message: '请输入限购数量', trigger: 'blur' }
    ],
    startTime: [
        { required: true, message: '请选择开始时间', trigger: 'change' }
    ],
    endTime: [
        { required: true, message: '请选择结束时间', trigger: 'change' },
        { validator: validateBatchEndTime, trigger: 'change' }
    ]
};

// 加载优惠券选项
const loadCouponOptions = () => {
    request.get('/coupon/selectCouponList', {
        page: 1,
        size: 500
    })
    .then(res => {
        // console.log(res)
        if (res.code === 200) {
            // 确保每个选项都是独立的对象
            couponOptions.value = res.data.selectCouponList
            console.log(couponOptions.value);
        } else {
            ElMessage.error(res.message || '获取优惠券列表失败');
        }
    })
    .catch(() => {
        ElMessage.error('因网络波动，获取优惠券列表失败');
    });
};
// 监听优惠券选择变化
const handleCouponSelectChange = (selected) => {
    // 根据选中的 couponId 获取完整的优惠券对象
    selectedCouponDetails.value = couponOptions.value
        .filter(item => selected.includes(item.templateId))
        .map(item => ({
            templateId: item.templateId,
            couponName: item.couponName,
            couponType: item.couponType
        }));
};
// 提交批量新增
const submitBatchAdd = () => {
    batchFormRef.value.validate((valid) => {
        if (!valid) {
            return;
        }
        console.log(selectedCouponDetails.value)
        const batchData = selectedCouponDetails.value.map(item => ({
            couponId: item.templateId,
            seckillNum: batchForm.value.seckillNum,
            limitNum: batchForm.value.limitNum,
            seckillStartTime: batchForm.value.startTime,
            seckillEndTime: batchForm.value.endTime
        }));
        console.log(batchData)
        // 调用批量新增API
        request.post('/sekill/batchAdd', batchData)
            .then(res => {
                console.log(res)
                if (res.message === "新增成功") {
                    ElMessage.success('批量新增成功');
                    showBatchAddDialog.value = false;
                    selectKillList(); // 刷新列表
                    // 重置表单
                    batchForm.value = {
                        selectedCoupons: [],
                        seckillNum: 1,
                        limitNum: 1,
                        startTime: '',
                        endTime: ''
                    };
                    selectedCouponDetails.value = [];
                } else {
                    ElMessage.error(res.message || '批量新增失败');
                }
            })
            .catch(() => {
                ElMessage.error('因网络波动，批量新增失败');
            });
    });
};
//批量删除按钮
const handleBatchDelete = () => {
    console.log(selectedRows.value,2342344);
    if (selectedRows.value.length === 0) {
        ElMessage.warning("请选择要删除的数据");
        return;
    }
     // 检查是否有errorStatus为0的行被选中
    // const hasUnprocessedRows = selectedRows.value.some(row =>new Date()>new Date(row.seckillEndTime));
    // if (hasUnprocessedRows) {
    //     ElMessage.warning('未开始的秒杀不能删除');
    //     return;
    // }
    ElMessageBox.confirm(
        `确认删除选中的 ${selectedRows.value.length} 条数据吗？`,
        "提示",
        {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
        }
    )
        .then(() => {
            // 获取所有选中行的ID
            const ids = selectedRows.value.map((item) => item.seckillId);
            console.log(ids);

            // 调用批量删除
            request.delete(`/sekill/deleteBatch?seckillIds=${ids}`)
                .then((res) => {
                    console.log(res);
                    if(res.message == "删除成功"){
                        ElMessage.success('批量删除成功');
                        selectKillList(); // 刷新列表
                    }
                })
                .catch(err => {
                    console.error('批量删除失败:', err);
                    ElMessage.error('批量删除失败');
                });
        })
        .catch(() => {
            // 用户取消删除
            ElMessage.info("已取消删除");
        });
};
//表格里的删除按钮
const handleDelete = (row) => {
    console.log(row);
     ElMessageBox.confirm(
        '确认删除该条数据吗？',
        '提示',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
        }
    )
        .then(() => {
            // 调用删除API
            console.log(row.seckillId);
            request.delete(`/sekill/deleteById?seckillId=${row.seckillId}`)
                .then((res) => {
                    console.log(res);
                    if(res.message == "删除成功"){
                        ElMessage.success('删除成功');
                        selectKillList(); // 刷新列表
                    }
                })
                .catch(err => {
                    // console.error('删除失败:', err);
                    ElMessage.error('因网络波动，删除失败');
                });
        })
        .catch(() => {
            // 用户取消删除
            ElMessage.info('已取消删除');
        });
}
//表格中的编辑按钮
const handleEdit = (row) => {
    showEditDialog.value = true;
    // 复制数据到编辑表单
    editForm.value = {
        seckillId: row.seckillId,
        couponName: row.couponName,
        couponType: row.couponType,
        seckillNum: row.seckillNum,
        limitNum: row.limitNum,
        seckillStartTime: row.seckillStartTime,
        seckillEndTime: row.seckillEndTime
    };
    // 保存原始数据用于比较
    originalEditData.value = { ...editForm.value };
};


// 编辑相关的响应式变量
const showEditDialog = ref(false);
const editFormRef = ref(null);
const editForm = ref({
    seckillId: '',
    couponName: '',
    couponType: '',
    seckillNum: 1,
    limitNum: 1,
    seckillStartTime: '',
    seckillEndTime: '',
});

// 存储原始编辑数据
const originalEditData = ref(null);

// 检查是否有修改
const hasChanges = () => {
    if (!originalEditData.value) return false;
    
    return (
        editForm.value.seckillNum !== originalEditData.value.seckillNum ||
        editForm.value.seckillStartTime !== originalEditData.value.seckillStartTime ||
        editForm.value.seckillEndTime !== originalEditData.value.seckillEndTime
    );
};

// 验证编辑表单的结束时间
const validateEditEndTime = (rule, value, callback) => {
    if (!value) {
        callback(new Error('请选择结束时间'));
        return;
    }
    
    if (editForm.value.seckillStartTime && new Date(value) <= new Date(editForm.value.seckillStartTime)) {
        callback(new Error('结束时间必须晚于开始时间'));
        return;
    }
    
    callback();
};
// 禁用当前时间之前的日期
const disableBeforeNow = (time) => {
    return time.getTime() < Date.now();
};

// 验证开始时间
const validateStartTime = (rule, value, callback) => {
    if (!value) {
        callback(new Error('请选择开始时间'));
        return;
    }
    
    const startDate = new Date(value);
    const now = new Date();
    
    if (startDate < now) {
        callback(new Error('开始时间不能早于当前时间'));
        return;
    }
    
    if (editForm.value.seckillEndTime && startDate >= new Date(editForm.value.seckillEndTime)) {
        callback(new Error('开始时间必须早于结束时间'));
        return;
    }
    
    callback();
};
// 编辑表单验证规则
const editRules = {
    seckillNum: [
        { required: true, message: '请输入秒杀数量', trigger: 'blur' },
        { type: 'number', min: 1, message: '秒杀数量必须大于0', trigger: 'blur' }
    ],
    seckillStartTime: [
        { required: true, message: '请选择开始时间', trigger: 'change' },
        { validator: validateStartTime, trigger: 'change' }
    ],
    seckillEndTime: [
        { required: true, message: '请选择结束时间', trigger: 'change' },
        { validator: validateEditEndTime, trigger: 'change' }
    ]
};
// 提交编辑
const submitEdit = () => {
    // 首先检查是否有修改
    if (!hasChanges()) {
        ElMessage.warning('请至少修改一项内容');
        return;
    }

    editFormRef.value.validate((valid) => {
        if (!valid) return;

        // 构造提交的数据
        const editData = {
            seckillId: editForm.value.seckillId,
            seckillNum: editForm.value.seckillNum,
            seckillStartTime: editForm.value.seckillStartTime,
            seckillEndTime: editForm.value.seckillEndTime
        };
        // console.log(editData);
        // 调用更新API
        request.put('/sekill/updateSeckill', editData)
            .then(res => {
                 console.log(res);
                if (res.message === "编辑成功") {
                    ElMessage.success('编辑成功');
                    showEditDialog.value = false;
                    selectKillList(); // 刷新列表
                } else {
                    ElMessage.error(res.message || '编辑失败');
                }
            })
            .catch(() => {
                ElMessage.error('因网络波动，编辑失败');
            });
    });
};
</script>

<style>
.crud-container {
    background-color: #fff;
    padding: 20px;
    border-radius: 4px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.search-area {
    margin-bottom: 20px;
    padding-bottom: 20px;
    border-bottom: 1px solid #ebeef5;
}

.operation-area {
    margin-bottom: 20px;
}

.table-area {
    margin-bottom: 20px;
}

.pagination-area {
    display: flex;
    justify-content: flex-end;
    margin-top: 20px;
}

.pagination-area span {
    padding-left: 10px;
}

.search-form {
    display: flex;
    flex-wrap: wrap;
    gap: 10px;
}

.el-button [class*="el-icon"]+span {
    margin-left: 5px;
}

.search-form .el-form-item {
    min-width: 190px;
}

.el-form-item span {
    /* padding-left: 10px; */
}

.el-formitem {
    width: 225px;
}

/* 时间选择器 */
.demo-datetime-picker {
    display: flex;
    width: 100%;
    padding: 0;
    flex-wrap: wrap;
    justify-content: space-around;
    align-items: stretch;
}

.demo-datetime-picker .block {
    padding: 30px 0;
    text-align: center;
}

.batch-add-container {
    padding: 0 20px;
}

.selected-preview {
    margin-top: 20px;
    padding: 15px;
    border: 1px solid #ebeef5;
    border-radius: 4px;
}

.selected-preview h3 {
    margin-bottom: 15px;
    color: #606266;
    font-size: 14px;
}

/* 修复时间选择器样式 */
.el-date-editor.el-input__wrapper {
    width: auto !important;
}

.el-date-editor .el-range-separator {
    width: auto;
    padding: 0 5px;
}

.el-date-editor--datetimerange {
    --el-date-editor-width: 600px;
}

.el-dialog {
    min-width: 900px;
}

/* 确保表单项在小屏幕上也能完整显示 */
.el-form-item {
    margin-bottom: 22px;
}

.el-form-item__content {
    flex-wrap: nowrap;
}

/* 优化时间选择器在小屏幕上的显示 */
.el-date-range-picker {
    --el-date-range-picker-width: 800px;
    min-width: 800px;
}

.el-date-range-picker .el-date-range-picker__content {
    margin: 0 10px;
}

.el-date-range-picker__header {
    margin: 0 10px;
}

/* 自定义时间选择器样式 */
.time-picker-item {
    margin-bottom: 20px;
}

.time-picker-item :deep(.el-date-editor) {
    width: 600px !important;
}

.time-picker-item :deep(.el-input__wrapper) {
    width: 600px !important;
}

:deep(.custom-date-picker) {
    width: 800px !important;
}

:deep(.custom-date-picker) .el-date-range-picker__content {
    width: 380px !important;
}

:deep(.custom-date-picker) .el-date-range-picker__header {
    margin-bottom: 10px;
}
</style>